package tool

import (
	"crypto"
	"crypto/md5"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/hex"
	"encoding/pem"
	"fmt"
	"sort"
	"strings"
)

func SignNotify(dataMap map[string]interface{}, secret, subPublicKey, TarSignature string) bool {
	var sortKeys []string
	for key := range dataMap {
		sortKeys = append(sortKeys, key)
	}
	sort.Strings(sortKeys) // 对 key 进行排序

	// 2. 按照 key1=val1&key2=val2&key3=val3....&key=md5秘钥生成加密字符串
	var sb strings.Builder
	for _, k := range sortKeys {
		sb.WriteString(fmt.Sprintf("%s=%v&", k, dataMap[k]))
	}
	sb.WriteString(fmt.Sprintf("key=%s", secret))
	str := sb.String()

	// 3: MD5 hash the string and convert to uppercase
	tempHash := md5.Sum([]byte(str))

	md5Str := hex.EncodeToString(tempHash[:])

	md5Str = strings.ToUpper(md5Str)
	fmt.Println("md5---\n", md5Str)

	// RSA公钥字符串
	rsaPublicKey := "-----BEGIN PUBLIC KEY-----\n" + subPublicKey + "\n-----END PUBLIC KEY-----"
	// 要验签的数据
	data := md5Str
	// Base64编码的签名字段
	signatureBase64 := TarSignature
	// 解码PEM格式的RSA公钥
	block, _ := pem.Decode([]byte(rsaPublicKey))
	if block == nil {
		return false
	}
	// 解析RSA公钥
	publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return false
	}
	// 将Base64编码的签名解码
	signature, err := base64.StdEncoding.DecodeString(signatureBase64)
	if err != nil {
		return false
	}
	// 计算数据的MD5哈希值
	//hash := md5.Sum([]byte(data))
	hash := sha256.Sum256([]byte(data))
	// 使用公钥进行验签
	err = rsa.VerifyPKCS1v15(publicKey.(*rsa.PublicKey), crypto.SHA256, hash[:], signature)
	if err != nil {
		return false
	} else {
		return true
	}
}
